﻿using UnityEngine;
using System;
using System.Threading;

namespace GameBasic
{
    public class PoolingTask
    {
        // volatile ?
        protected float progress = -1;
        // lambda cache
        WaitCallback execute;

        /// <summary>
        /// Submit to thread pool
        /// </summary>
        public void Submit()
        {
            if (execute == null)
                execute = Execute;

            if (!IsRunning())
            {
                progress = 0;
                ThreadPool.QueueUserWorkItem(execute);
            }
        }

        /// <summary>
        /// Execute the task, called from thread pool.
        /// </summary>
        public void Execute(object obj = null)
        {
            try
            {
                progress = 0;
                ExecuteImpl();
            }
            catch (Exception e){
                Debug.LogException(e);
            }

            progress = 1;
        }

        protected virtual void ExecuteImpl()
        {

        }

        public float GetProgress()
        {
            return progress;
        }

        public bool IsRunning()
        {
            return progress > 0;
        }

        public bool IsDone()
        {
            return progress >= 1;
        }
    }
}